package com.changgou.order.controller;

import com.changgou.entity.Result;
import com.changgou.order.feign.OrderFeign;
import com.changgou.order.pojo.Order;
import com.changgou.pay.feign.WxPayFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Map;

@Controller
@RequestMapping("/wxpay")
public class WebPayController {

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private WxPayFeign wxPayFeign;

    /**
     * 返回的数据
     *      {
     *         "nonce_str": "MQXs5ZhQxDLN4vOA",
     *         "code_url": "weixin://wxpay/bizpayurl?pr=NBfaVhf",
     *         "appid": "wx8397f8696b538317",
     *         "sign": "1572B5017115DD9C73E040FFBE7C69C2D463AE91254FFF687792246A0A0BEB5E",
     *         "trade_type": "NATIVE",
     *         "return_msg": "OK",
     *         "result_code": "SUCCESS",
     *         "mch_id": "1473426802",
     *         "return_code": "SUCCESS",
     *         "prepay_id": "wx27104346454190258840d8f51924753200"
     *         "orderId" : "1234123543251"
     *         "payMoney" : "100"
     *     }
     * @param orderId
     * @param model
     * @return
     */
    @GetMapping
    public String wxPay(String orderId, Model model){
        //通过feign进行远程调用
        Order order = orderFeign.findById(orderId).getData();
        if( order == null ){
            //没有当前订单,跳转到出错页面
            return "fail";
        }

        //判断支付状态,非0代表已付款
        if(!"0".equals(order.getPayStatus())){
            return "fail";//出错页面
        }

        //获取微信统一下单的结果集
        Result nativePayResult = wxPayFeign.nativePay(orderId, order.getPayMoney());

        //没有返回统一下单结果,跳转到出错页面
        if(nativePayResult.getData() == null){
            return "fail";
        }
        Map payMap = (Map) nativePayResult.getData();
        payMap.put("orderId",orderId);
        payMap.put("payMoney",order.getPayMoney());

        //参数封装
        model.addAllAttributes(payMap);

        //跳转微信支付二维码页面
        //携带参数,支付金额和订单ID
        return "wxpay";
    }


    /**
     * 支付成功后,跳转至支付成功页面.
     * @param payMoney
     * @return
     */
    @GetMapping("/toPaySuccess")
    public String toPaySuccess(Integer payMoney,Model model){
        model.addAttribute("payMoney",payMoney);
        //跳转到支付成功页面
        return "paysuccess";
    }

}
